package controller.admin;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "AdminUserAddServlet", value = "/admin/user_add")
public class AdminUserAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UserService us = new UserService();
        String userName = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        User user = new User(userName, email, password, name, phone, address);

        //几个必填项不能为空
        if (!(user.getUsername() != null && !"".equals(user.getUsername()) &&
                user.getEmail() != null && !"".equals(user.getEmail()) &&
                user.getPassword() != null && !"".equals(user.getPassword()))) {
            request.setAttribute("failMsg", "添加失败！用户名、邮箱、密码不能为空");
            request.getRequestDispatcher("user_add.jsp").forward(request, response);
            return;
        }

        request.setAttribute("u", user);

        //判断用户名是否存在
        boolean usernameExist = us.isUsernameExist(user.getUsername());
        if (usernameExist) {
            request.setAttribute("failMsg", "用户名已存在！");
            request.getRequestDispatcher("user_add.jsp").forward(request, response);
            return;
        }
        //判断邮箱是否存在
        boolean emailExist = us.isEmailExist(user.getEmail());
        if (emailExist) {
            request.setAttribute("failMsg", "邮箱已存在！");
            request.getRequestDispatcher("user_add.jsp").forward(request, response);
            return;
        }

        try {
            boolean flag = us.register(user);
            if (flag) {
                request.removeAttribute("u");
                request.setAttribute("msg", "添加成功！");
                request.getRequestDispatcher("user_list").forward(request, response);
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("failMsg", "添加失败！");
        request.getRequestDispatcher("user_add.jsp").forward(request, response);
    }
}
